using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using WPF_MVVM_Test.MVVM_Model.Bom;
using WPF_MVVM_Test.MVVM_Model.Bom.Bom;
using WPF_MVVM_Test.Services.Bom;

namespace WPF_MVVM_Test.MVVM_View.Bom
{
    /// <summary>
    /// BomEditWindow.xaml 的交互逻辑
    /// </summary>
    public partial class BomEditWindow : Window
    {
        private BomItem _originalBomItem;
        private BomEditViewModel _viewModel;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="bomItem">要编辑的BOM项目</param>
        public BomEditWindow(BomItem bomItem)
        {
            InitializeComponent();
            
            _originalBomItem = bomItem;
            
            // 创建ViewModel
            _viewModel = new BomEditViewModel(bomItem);
            
            // 设置数据上下文
            DataContext = _viewModel;
        }

        /// <summary>
        /// 保存按钮点击事件
        /// </summary>
        private async void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 验证输入
                if (string.IsNullOrWhiteSpace(_viewModel.BomNumber))
                {
                    MessageBox.Show("BOM编号不能为空！", "验证错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (string.IsNullOrWhiteSpace(_viewModel.ProductName))
                {
                    MessageBox.Show("产品名称不能为空！", "验证错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // TODO: 这里应该调用API保存数据
                // 示例：await bomService.UpdateBomAsync(_viewModel.EditingBomItem);
                
                // 暂时显示保存成功的消息
                var result = MessageBox.Show(
                    $"确定要保存以下BOM信息的修改吗？\n\n" +
                    $"BOM编号: {_viewModel.BomNumber}\n" +
                    $"产品名称: {_viewModel.ProductName}\n" +
                    $"版本: {_viewModel.Version}\n" +
                    $"备注: {_viewModel.Remark}",
                    "确认保存",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    // 将编辑的数据复制回原对象
                    _viewModel.CopyToOriginal(_originalBomItem);
                    
                    MessageBox.Show("BOM信息保存成功！", "保存成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    
                    // 设置对话框结果为成功
                    DialogResult = true;
                    Close();
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show("确定要取消编辑吗？未保存的修改将丢失。", "确认取消", 
                                       MessageBoxButton.YesNo, MessageBoxImage.Question);
            
            if (result == MessageBoxResult.Yes)
            {
                DialogResult = false;
                Close();
            }
        }

    }

    /// <summary>
    /// BOM编号颜色转换器
    /// </summary>
    public class BomNumberColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is string bomNumber && !string.IsNullOrEmpty(bomNumber))
            {
                return new SolidColorBrush(Colors.Blue);
            }
            return new SolidColorBrush(Colors.Black);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    /// <summary>
    /// BOM编号装饰转换器
    /// </summary>
    public class BomNumberDecorationConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is string bomNumber && !string.IsNullOrEmpty(bomNumber))
            {
                return TextDecorations.Underline;
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    /// <summary>
    /// BOM编辑ViewModel
    /// </summary>
    public class BomEditViewModel
    {
        private BomItem _editingBomItem;
        private readonly BomCompositionService _bomCompositionService;

        public BomEditViewModel(BomItem bomItem)
        {
            // 创建一个副本用于编辑，避免直接修改原对象
            _editingBomItem = new BomItem
            {
                Id = bomItem.Id,
                BomNumber = bomItem.BomNumber,
                IsSystemNumber = bomItem.IsSystemNumber,
                IsDefault = bomItem.IsDefault,
                Version = bomItem.Version,
                ProductId = bomItem.ProductId,
                ProductName = bomItem.ProductName,
                ColorCode = bomItem.ColorCode,
                Unit = bomItem.Unit,
                DailyOutput = bomItem.DailyOutput,
                Remark = bomItem.Remark,
                ProcessRouteId = bomItem.ProcessRouteId,
                ProcessRouteName = bomItem.ProcessRouteName,
                CreatedTime = bomItem.CreatedTime,
                LastUpdatedTime = bomItem.LastUpdatedTime,
                ItemCount = bomItem.ItemCount
            };

            // 初始化服务
            _bomCompositionService = new BomCompositionService();

            // 初始化BOM组成数据
            BomCompositionItems = new ObservableCollection<BomCompositionItem>();

            // 加载BOM组成数据
            LoadBomCompositionAsync();
        }

        // BOM基础信息属性
        public string Id => _editingBomItem.Id;
        public string BomNumber
        {
            get => _editingBomItem.BomNumber;
            set => _editingBomItem.BomNumber = value;
        }
        public bool IsSystemNumber
        {
            get => _editingBomItem.IsSystemNumber;
            set => _editingBomItem.IsSystemNumber = value;
        }
        public bool IsDefault
        {
            get => _editingBomItem.IsDefault;
            set => _editingBomItem.IsDefault = value;
        }
        public string Version
        {
            get => _editingBomItem.Version;
            set => _editingBomItem.Version = value;
        }
        public string ProductId => _editingBomItem.ProductId;
        public string ProductName
        {
            get => _editingBomItem.ProductName;
            set => _editingBomItem.ProductName = value;
        }
        public string ColorCode
        {
            get => _editingBomItem.ColorCode;
            set => _editingBomItem.ColorCode = value;
        }
        public string Unit
        {
            get => _editingBomItem.Unit;
            set => _editingBomItem.Unit = value;
        }
        public decimal DailyOutput
        {
            get => _editingBomItem.DailyOutput;
            set => _editingBomItem.DailyOutput = value;
        }
        public string Remark
        {
            get => _editingBomItem.Remark;
            set => _editingBomItem.Remark = value;
        }
        public string ProcessRouteId => _editingBomItem.ProcessRouteId;
        public string ProcessRouteName
        {
            get => _editingBomItem.ProcessRouteName;
            set => _editingBomItem.ProcessRouteName = value;
        }
        public DateTime CreatedTime => _editingBomItem.CreatedTime;
        public DateTime LastUpdatedTime => _editingBomItem.LastUpdatedTime;
        public int ItemCount
        {
            get => _editingBomItem.ItemCount;
            set => _editingBomItem.ItemCount = value;
        }

        // BOM组成数据
        public ObservableCollection<BomCompositionItem> BomCompositionItems { get; set; }

        /// <summary>
        /// 加载BOM组成数据
        /// </summary>
        private async void LoadBomCompositionAsync()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine($"开始加载BOM组成数据，BOM ID: {_editingBomItem.Id}");

                var response = await _bomCompositionService.GetBomTreeAsync(_editingBomItem.Id);

                if (response.IsSuc && response.Data != null)
                {
                    System.Diagnostics.Debug.WriteLine($"BOM组成数据加载成功，数据数量: {response.Data.Count}");

                    // 清空现有数据
                    BomCompositionItems.Clear();

                    // 将树形数据扁平化显示
                    var flattenedItems = FlattenBomTree(response.Data);
                    
                    foreach (var item in flattenedItems)
                    {
                        BomCompositionItems.Add(item);
                    }

                    System.Diagnostics.Debug.WriteLine($"BOM组成数据扁平化完成，总数量: {BomCompositionItems.Count}");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"BOM组成数据加载失败: {response.Msg}，使用测试数据");
                    
                    // 如果API失败，使用测试数据
                    LoadTestData();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"BOM组成数据加载异常: {ex.Message}，使用测试数据");
                
                // 异常时使用测试数据
                LoadTestData();
            }
        }

        /// <summary>
        /// 加载测试数据
        /// </summary>
        private void LoadTestData()
        {
            var testData = BomCompositionItem.GetTestData();
            BomCompositionItems.Clear();
            
            var flattenedItems = FlattenBomTree(testData.ToList());
            foreach (var item in flattenedItems)
            {
                BomCompositionItems.Add(item);
            }
            
            System.Diagnostics.Debug.WriteLine($"测试数据加载完成，数量: {BomCompositionItems.Count}");
        }

        /// <summary>
        /// 将树形结构扁平化
        /// </summary>
        /// <param name="items">树形数据</param>
        /// <param name="level">层级（用于缩进显示）</param>
        /// <returns></returns>
        private System.Collections.Generic.List<BomCompositionItem> FlattenBomTree(
            System.Collections.Generic.List<BomCompositionItem> items, int level = 0)
        {
            var result = new System.Collections.Generic.List<BomCompositionItem>();

            foreach (var item in items)
            {
                // 根据层级调整产品名称显示（添加缩进）
                var displayName = item.ProductName;
                if (level > 0)
                {
                    displayName = new string(' ', level * 4) + "└─ " + displayName;
                }

                // 创建显示项
                var displayItem = new BomCompositionItem
                {
                    Sequence = item.Sequence,
                    ProductName = displayName,
                    ProductNumber = item.ProductNumber,
                    Specification = item.Specification,
                    Unit = item.Unit,
                    BomNumber = item.BomNumber,
                    BomVersion = item.BomVersion,
                    UsageQuantity = item.UsageQuantity,
                    UsageRatio = item.UsageRatio,
                    IsExpandable = item.IsExpandable,
                    Children = item.Children
                };

                result.Add(displayItem);

                // 递归处理子项
                if (item.Children != null && item.Children.Count > 0)
                {
                    result.AddRange(FlattenBomTree(item.Children, level + 1));
                }
            }

            return result;
        }

        /// <summary>
        /// 将编辑的数据复制回原对象
        /// </summary>
        public void CopyToOriginal(BomItem target)
        {
            target.BomNumber = _editingBomItem.BomNumber;
            target.IsSystemNumber = _editingBomItem.IsSystemNumber;
            target.IsDefault = _editingBomItem.IsDefault;
            target.Version = _editingBomItem.Version;
            target.ProductName = _editingBomItem.ProductName;
            target.ColorCode = _editingBomItem.ColorCode;
            target.Unit = _editingBomItem.Unit;
            target.DailyOutput = _editingBomItem.DailyOutput;
            target.Remark = _editingBomItem.Remark;
            target.ProcessRouteName = _editingBomItem.ProcessRouteName;
            target.ItemCount = _editingBomItem.ItemCount;
            target.LastUpdatedTime = DateTime.Now; // 更新最后修改时间
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            _bomCompositionService?.Dispose();
        }
    }
}